package com.wlcorp.forcazamis.sys.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionServlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class FileUploadUtil {
	private static final int BUFFERLEN = 1024*1024;
	/**
	 * @param inputStream	图片InputStream
	 * @param path			图片存储路径
	 * TODO struts FormFile上传文件时使用
	 */
	public static void saveFile(InputStream inputStream,String path){

		byte[] buffer=new byte[BUFFERLEN];
		int readedLen = 0;
		try {
			OutputStream out = new FileOutputStream(path);
			while((readedLen = inputStream.read(buffer,0,BUFFERLEN))!=-1) {
				try {
					out.write(buffer,0,readedLen);
				} catch(Exception e) {
					System.out.println(e.getMessage());
					return;
				}
			}
			out.close();
			inputStream.close();
		} catch(IOException ioe) {
			System.out.println(ioe.getMessage());
			return;
		}
	}
	
	/**
	 * @param servlet
	 * @param request
	 * @param response
	 * @param path
	 * TODO smartUpload上传文件时使用
	 */
	public static void saveFile(File file,String path) {
        
        try{
        	file.saveAs(path);
        } catch(Exception ex){
        	ex.printStackTrace();
        }
	}
	
	public static SmartUpload getSmartUpload(ActionServlet servlet,HttpServletRequest request,HttpServletResponse response){
		SmartUpload smartUpload = new SmartUpload();
        try {
			smartUpload.initialize(servlet, request, response);
			smartUpload.setMaxFileSize(BUFFERLEN);
			smartUpload.setTotalMaxFileSize(BUFFERLEN);
			smartUpload.upload();
		} catch (SmartUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
		return smartUpload;
	}
}
